package cn.itcast.service.impl;

import cn.itcast.dao.AreaDao;
import cn.itcast.domain.Area;
import cn.itcast.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AreaServiceImpl implements AreaService {

    @Autowired
    private AreaDao areaDao;
    /**
     * exlce表一键导入
     * @param areas
     * @return
     */
    @Override
    public String areaImport(List<Area> areas) {

        try {
            areaDao.saveAll(areas);
            return "OK";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "NO";
    }

    /**
     * 分页查询 / 复杂查询方法
     * @param page
     * @param rows
     * @return
     */
    @Override
    public Page<Area> areaPageQuery(int page, int rows,Area area) {
        //升序排序
        Sort sort = new Sort(Sort.Direction.ASC,"id");

        //构建模糊匹配条件
        ExampleMatcher matcher =ExampleMatcher.matching()
                .withMatcher("province",ExampleMatcher.GenericPropertyMatchers.contains())  //省份
                .withMatcher("city",ExampleMatcher.GenericPropertyMatchers.contains())  //城市
                .withMatcher("district",ExampleMatcher.GenericPropertyMatchers.contains()); //区县
        Pageable pageable = PageRequest.of(page-1,rows,sort);    //分页
        Example example= Example.of(area,matcher);     //模糊匹配
        Page<Area> all = areaDao.findAll(example,pageable);

        return all;
    }

    /**
     * 添加的方法
     * @param area
     */
    @Override
    public void addArea(Area area) {
        areaDao.save(area);
    }

    /**
     * 删除的方法
     * @param ids
     */
    @Override
    public void delBatch(String ids) {
        //将字符串根据逗号解析成为字符串数组
        String[] strs = ids.split(",");
        //循环数组,并转换为int类型
        for (String str : strs) {
//            int i = Integer.parseInt(str);

            areaDao.deleteById(str);
        }

    }


}
